from typing import Any, Dict, Optional
from fastapi import HTTPException, status

class APIResponse:
    """统一的API响应格式"""
    
    @staticmethod
    def success(data: Any = None, message: str = "操作成功") -> Dict[str, Any]:
        """成功响应"""
        response = {
            "success": True,
            "message": message,
            "code": 200
        }
        if data is not None:
            response["data"] = data
        return response
    
    @staticmethod
    def error(message: str = "操作失败", code: int = 400, data: Any = None) -> Dict[str, Any]:
        """错误响应"""
        response = {
            "success": False,
            "message": message,
            "code": code
        }
        if data is not None:
            response["data"] = data
        return response
    
    @staticmethod
    def created(data: Any = None, message: str = "创建成功") -> Dict[str, Any]:
        """创建成功响应"""
        response = {
            "success": True,
            "message": message,
            "code": 201
        }
        if data is not None:
            response["data"] = data
        return response

class APIException(HTTPException):
    """自定义API异常"""
    
    def __init__(self, message: str = "内部服务器错误", status_code: int = 500, data: Any = None):
        self.message = message
        self.data = data
        super().__init__(status_code=status_code, detail=message)

# 常用错误响应
class CommonErrors:
    """常用错误响应"""
    
    @staticmethod
    def permission_denied(message: str = "权限不足"):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=APIResponse.error(message, 403)
        )
    
    @staticmethod
    def unauthorized(message: str = "未授权访问"):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=APIResponse.error(message, 401),
            headers={"WWW-Authenticate": "Bearer"}
        )
    
    @staticmethod
    def not_found(message: str = "资源不存在"):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=APIResponse.error(message, 404)
        )
    
    @staticmethod
    def bad_request(message: str = "请求参数错误"):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=APIResponse.error(message, 400)
        ) 